#include <stdio.h>
#include <iostream>
#include <string>

#include "IO/PDB2Dyn.h"
#include "IO/Dyn2PDB.h"
#include "Config.h"
#include "DynamoWrapper.h"
#include "model/System.h"

using std::cerr;
using std::cout;
using std::endl;

std::string generate_dynamo_file(const std::string& pdb_file)
{
    // Check if pdb_file is actually a pdb file
    const std::string ext = pdb_file.substr(pdb_file.length() - 3, 3);
    if (ext != "pdb" && ext != "PDB")
        return pdb_file;

    cout << "Input is a PDB file, converting to Dynamo format" << endl;

    PDB2Dyn o(pdb_file.c_str());
    unsigned int atoms = o.convert();
    cout << "System contains " << atoms << " atoms." << endl;
    cout << "Wrote DYNAMO file " << o.getOutFname() << endl;
    return o.getOutFname();
}

int main(int argc, char** argv)
{
    if (argc <= 1)
    {
        cerr << "Usage:" << argv[0] << " <PDB infile> [config file]" << endl;
        return EXIT_FAILURE;
    }

    const char* cfg_file = (argc > 2) ? argv[2] : NULL;
    std::string dynamo_file = argv[1];

    Config cfg(cfg_file);
    try
    {
        cfg.read();
    }
    catch (const std::exception& ex)
    {
        cerr << "Coudn't read config file " << cfg.getConfigFileName() << endl;
        return EXIT_FAILURE;
    }

    try
    {
        dynamo_file = generate_dynamo_file(dynamo_file);
    }
    catch (const std::exception& ex)
    {
        cerr << ex.what() << "\n";
    }

    if (cfg.isDryRun()) return EXIT_SUCCESS;

    DynamoWrapper dyn;
    try
    {
        dyn.run(cfg, dynamo_file);
        dyn.runxyz(cfg, dynamo_file);

        Dyn2PDB dyn2pdb;
        dyn2pdb.read_xyz("tinker.frame00000.xyz");
        dyn2pdb.update_pdb(argv[1], "a_out.pdb");
    }
    catch (const std::exception& ex)
    {
        cerr << ex.what() << endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

